package com.qf.servlet;

import com.qf.pojo.Cart;
import com.qf.pojo.CartItem;
import com.qf.pojo.Product;
import com.qf.pojo.User;
import com.qf.service.ProductService;
import com.qf.service.impl.ProductServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/cart")

public class cartServlet extends baseServlet {
    //将购物车存储导sessio中
    public Cart getCart(HttpServletRequest request){
        //从session中获取cart
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        //先判断是否存在cart
        if (cart==null){
            cart = new Cart();
            request.getSession().setAttribute("cart",cart);
        }
        return cart;
}

    //将购物车项添加到购物车
    public void add2cart(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        //判断,用户是否登录,用户已经存在于session中
        User user = (User) request.getSession().getAttribute("user");
        //用户不存在
        if (user==null){
            //请求转发至登录界面
            request.getRequestDispatcher("/jsp/login.jsp").forward(request,response);
        }
        Cart cart = getCart(request);

            //用户存在,获取隐藏域中的数据
            String pid = request.getParameter("pid");
//            System.out.println(pid);
            //调用服务层,获取商品实体
            ProductService productService = new ProductServiceImpl();
            Product product = productService.findProductByid(pid);
            //获取商品数量
            String countnum = request.getParameter("count");
//            System.out.println(countnum);

            //转换成int类型
            int count = Integer.parseInt(countnum);
            //获取购物车实体
            //封装购物车,先获取购物车
//            Cart cart = getCart(request);
            //封装cart
            CartItem cartItem = new CartItem(product,count);
//            System.out.println(cartItem);
            cart.addItem2Cart(cartItem);
//            System.out.println(cart);
            //重定向到
            response.sendRedirect(request.getContextPath()+"/jsp/cart.jsp");


    }
    public void delCartItem(HttpServletRequest request,HttpServletResponse response) throws IOException {
        //获取参数pid
        String pid = request.getParameter("pid");
        //从session中获取购物车
        Cart cart = getCart(request);
        //调用cart中的删除方法
        cart.delCartItem(pid);
        //重定向
        response.sendRedirect(request.getContextPath()+"/jsp/cart.jsp");

    }
    public void clear(HttpServletRequest request,HttpServletResponse response) throws IOException {
        //从session中获取购物车
        Cart cart = getCart(request);
        //调用全部清除clear方法
        cart.clear();
        //重定向
        response.sendRedirect(request.getContextPath()+"/jsp/cart.jsp");

    }

}
